package com.linewell.system.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.linewell.commom.controller.BackendBaseController;
import com.linewell.system.model.SysDepartment;
import com.linewell.system.pagemodel.DataGrid;
import com.linewell.system.pagemodel.PageHelper;
import com.linewell.system.pagemodel.ReturnInfo;
import com.linewell.system.pagemodel.SimpleTreeNode;
import com.linewell.system.service.ISysDepartmentService;
import com.linewell.system.utils.ConfigProperty;
import com.linewell.system.utils.FileUploadUtil;
import com.linewell.system.utils.SimpleTreeUtil;

/**
 * 部门控制器 
 */
@Controller
@RequestMapping("/manage/sysDepartment")
public class SysDepartmentController extends BackendBaseController {

	private static final Log log = LogFactory.getLog(SysDepartmentController.class);

	@Autowired
	private ISysDepartmentService sysDepartmentService;

	/**
	 * 跳转到sys_department_list页
	 */
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request) {

		return super.index("/WEB-INF/pages/system/sys_department/sys_department_list.jsp", request);

	}

	/**
	 * 数据查询
	 */
	@ResponseBody
	@RequestMapping(value = "/dataGrid")
	public DataGrid dataGrid(@ModelAttribute SysDepartment c, PageHelper ph,HttpServletRequest request) {

		ph.setSort("createTime");
		ph.setOrder("desc");
		DataGrid dg = sysDepartmentService.datagrid(c, ph,getUserDepId(request));
		return dg;
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add")
	public String add(Map<String, Object> map) {
		map.put("saveUrl", "/manage/sysDepartment/addSave");
		return "/WEB-INF/pages/system/sys_department/sys_department_au.jsp";
	}

	/**
	 * 添加保存
	 */
	@ResponseBody
	@RequestMapping(value = "/addSave")
	public ReturnInfo addSave(@Valid SysDepartment sysDepartment, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
		if (b.getErrorCount() > 0) { // 数据校验
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if (sysDepartment != null) {
								
				if(file != null){
					try {
						String icon_url = FileUploadUtil.saveFile(file, request, ConfigProperty.getProperty("fileUplaodPath", "config") + "icon");
						sysDepartment.setIcon(icon_url);
					} catch (Exception e) {
						log.info("上传异常"+e.getMessage());
					}
				}
				
				if (sysDepartment.getDepPId() == 0) {
					sysDepartment.setDepPId(null);
				}
				try {
					sysDepartmentService.save(sysDepartment);
				} catch (Exception e) {
					log.info("保存失败" + e.getMessage());
					result.setMsg("保存失败！");
					result.setSuccess(1);
				}
			}
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/edit")
	public String edit(String id, Map<String, Object> map) {
		log.info(id);
		map.put("saveUrl", "/manage/sysDepartment/editSave");
		if (id != null) {
			List<SysDepartment> model = sysDepartmentService.get(id);
			map.put("model", model.get(0));
		}
		return "/WEB-INF/pages/system/sys_department/sys_department_au.jsp";
	}

	/**
	 * 修改保存
	 */
	@ResponseBody
	@RequestMapping(value = "/editSave")
	public ReturnInfo editSave(@Valid SysDepartment sysDepartment, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {

		if (b.getErrorCount() > 0) { // 数据校验
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if (sysDepartment != null) {

				if(file != null){
					try {
						String icon_url = FileUploadUtil.saveFile(file, request, getConfigAttr("fileUplaodPath") + "icon");
						sysDepartment.setIcon(icon_url);
					} catch (Exception e) {
						log.info("上传异常"+e.getMessage());
					}
				}

				if (!sysDepartment.getDepPId().equals(sysDepartment.getDepId())) {

					if (sysDepartment.getDepPId() == 0) {
						sysDepartment.setDepPId(null);
					}

					try {
						 sysDepartmentService.update(sysDepartment);
						 //sysDepartmentService.saveOrUpdate(sysDepartment);
					} catch (Exception e) {
						log.info("修改失败" + e.getMessage());
						result.setMsg("修改失败！");
						result.setSuccess(1);
					}

				} else {
					result.setMsg("上级部门不能是自身！");
					result.setSuccess(1);
				}

			}
		}

		return result;
	}

	/**
	 * 删除（物理删除）
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public ReturnInfo delete(Integer id, ReturnInfo result, HttpServletRequest request) {
		log.info(id);
		if (id != null) {
			if (getUserDepId(request) == null) { // 超级管理员

				try {
					sysDepartmentService.deleteAll(id);
				} catch (Exception e) {
					log.info("删除异常" + e.getMessage());
					result.setMsg("删除失败！");
					result.setSuccess(1);
				}
			} else if (getUserDepId(request).equals(id.intValue())) {
				result.setMsg("你不能删除自己的部门！");
				result.setSuccess(1);
			} else {
				try {
					sysDepartmentService.deleteAll(id);
				} catch (Exception e) {
					log.info("删除异常" + e.getMessage());
					result.setMsg("删除失败！");
					result.setSuccess(1);
				}
			}

		}

		return result;
	}

	/**
	 * 移除（逻辑删除）
	 */
	@ResponseBody
	@RequestMapping(value = "/remove")
	public ReturnInfo remove(Integer id, ReturnInfo result, HttpServletRequest request) {
		log.info("移除部门" + id);
		log.info("用户所处部门：" + getUserDepId(request));
		if (id != null) {

			if (getUserDepId(request) == null) { // 超级管理员

				try {
					sysDepartmentService.removeAll(id);
				} catch (Exception e) {
					log.info("移除异常" + e.getMessage());
					result.setMsg("移除失败！");
					result.setSuccess(1);
				}
			} else if (getUserDepId(request).equals(id.intValue())) {
				result.setMsg("你不能移除自己的部门！");
				result.setSuccess(1);
			} else {
				try {
					sysDepartmentService.removeAll(id);
				} catch (Exception e) {
					log.info("移除异常" + e.getMessage());
					result.setMsg("移除失败！");
					result.setSuccess(1);
				}
			}

		}

		return result;
	}

	/**
	 * 获取部门信息
	 */
	@ResponseBody
	@RequestMapping(value = "/getAllDepaetment")
	public ReturnInfo getAllDepaetment(Integer flag,Integer type,HttpServletRequest request) {
		ReturnInfo info = new ReturnInfo();
		try {
			List<SysDepartment> lst = sysDepartmentService.getAllDepaetment(type,getUserDepId(request));
			// log.info(lst);
			List<SimpleTreeNode> lstTree = null;
			if (lst != null && lst.isEmpty() == false) {
				SimpleTreeUtil treeUtil = new SimpleTreeUtil();
				treeUtil.setLstAll(lst);
				lstTree = treeUtil.findById(null);
			}

			if (flag.intValue() == 0) {
				if (getUserDepId(request) == null || getUserDepId(request) == 0) {
					SimpleTreeNode flat = new SimpleTreeNode(0, "平台");
					lstTree.add(0, flat);
				}
			} else if (flag.intValue() == 2) {
				SimpleTreeNode flat = new SimpleTreeNode(0, "请选择所属的单位");
				lstTree.add(0, flat);
			}

			info.setObj(lstTree);

		} catch (Exception e) {
			log.info("异常" + e.getMessage());
		}
		return info;
	}
	
	/**
	 * 根据提供的名称获得单个resources目录下config.properties属性值 方法一(不能静态.....)
	 * (也可以使用同一获取工具ConfigProperty.getProperty("fileUplaodPath", "config"))
	 */
	public String getConfigAttr(String str) {

		String attrStr = null;
		Properties prop = new Properties();
		InputStream is = this.getClass().getResourceAsStream("/config.properties");
		try {
			prop.load(is);
			attrStr = prop.getProperty(str);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return attrStr;

	}

}
